/*
*************************************************************************
*西瑞克斯研发管理系统
*版 本: 1.0   
*日 期：02/16/2012    
*作 者： 王浩 QQ：873987060   
*************************************************************************   
*/ 
package com.application.systemmanager.service;  

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.springframework.scheduling.quartz.CronTriggerBean;

import com.application.systemmanager.entity.SystemConfig;
import com.application.yfsmsrecord.entity.YfSmsrecord;
import com.application.yfsmsrecord.service.YfSmsrecordService;
import com.manager.commons.CommonUtil;
import com.manager.commons.DateUtil;
import com.manager.workflow.WorkFlowConstants;
import com.manager.workflow.core.WorkFlowCommon;
import com.manager.workflow.entity.BusWorkItem;

/**   
 * TODO 定时任务处理类 
 * @author  Alex   
 * @since  jdk1.6   */
public class QuartzConfigService {
	private static final Logger logger = Logger.getLogger(QuartzConfigService.class);
	/**
	 * 注入的定时器调度对象
	 */
	private Scheduler scheduler;
    
	private SystemManagerService systemManagerService;
	
	private WorkFlowCommon workFlowCommon;
	
	 private YfSmsrecordService yfSmsrecordService;


	/**
	 *  更新触发条件
	 * 
	 * @throws Exception 
	 */
	public void updateTrigger(SystemConfig warningConfig) throws Exception
	{
		CronTriggerBean trigger = (CronTriggerBean) scheduler.getTrigger("initTrigger", Scheduler.DEFAULT_GROUP);
		String oldCronExpression = trigger.getCronExpression()==null?"":trigger.getCronExpression();
		//取数据库中配置好的开始时间
		String days = warningConfig.getConfigValue();
		String newCronExpression = "";
		if(!"".equals(days))
		{
			newCronExpression = getCronExpression(days);
			//如果预先设置了触发条件
			if(!"".equals(oldCronExpression))
			{
				//如果相等，则表示用户并没有重新设定数据库中的任务时间，这种情况不需要重新任务
				if(!oldCronExpression.equalsIgnoreCase(newCronExpression))
				{
					trigger.setCronExpression(newCronExpression);
					logger.info("设置预警提示时间：" + newCronExpression);
					scheduler.rescheduleJob("initTrigger", Scheduler.DEFAULT_GROUP, trigger);
				}
			}
			else
			{
				trigger.setCronExpression(newCronExpression);
				scheduler.rescheduleJob("initTrigger", Scheduler.DEFAULT_GROUP, trigger);
			}
		}	
	}
	
	//获得预警信息
	public void planReportEarlyWarning(){
		if(CommonUtil.SMS_OPEN == 1){
			SystemConfig config = systemManagerService.findSystemConfigByCode("4100102");	
			int diff = 24;
			if(StringUtils.isNotBlank(config.getConfigValue())){
				diff = Integer.valueOf(config.getConfigValue());
			}
			Map queryMap = new HashMap();
			queryMap.put("type",new Long(10012));
			queryMap.put("diff",diff);
			List planReportList = workFlowCommon.getAllWarnTask(queryMap, null);
			if(planReportList!=null && planReportList.size()>0){
				for(Object obj : planReportList){
					BusWorkItem workItem = (BusWorkItem) obj;
					sendSms(workItem);
//					String tel = workItem.getTel();
//					String name = workItem.getRname();
//					String date = DateUtil.dateToString(workItem.getCompleteDate(), "yyyy-MM-dd");
//					System.out.println("发送短信：" + tel +  "     " + name + " 给您指派的任务，请及时完成，任务截止时间" + date);
				}
			}
		}
	
	}
	
	
	  private void sendSms(BusWorkItem workItem){
	    	YfSmsrecord smsrecord = new YfSmsrecord();
	    	smsrecord.setBussId(getString(workItem.getBussId()));
	    	smsrecord.setBussType(getLong(workItem.getBussType()));
	    	smsrecord.setOrg("");
	    	smsrecord.setReceNo(workItem.getTel());
	    	smsrecord.setReceUser(workItem.getRname2());
	    	smsrecord.setSendContent(workItem.getRname()+"指派给您新任务，请及时处理！");
	    	smsrecord.setSendTime(new Date());
	    	smsrecord.setWorkitmeId(workItem.getId());
	    	smsrecord.setCreateDate(new Date());
	    	smsrecord.setOperateid("-1");
	    	smsrecord.setSendType(new Long(1));
	    	smsrecord.setState(WorkFlowConstants.SMS_STATUS_1);
	    	yfSmsrecordService.insertObject(smsrecord);
	    	System.out.println("发送短信到" + smsrecord.getReceNo() + "  " + smsrecord.getReceUser());
	    	CommonUtil.smsSend.seneSms(smsrecord);
	    }
	  
	  
	  private Long getLong(Object o){
			if(o!=null){
				return Long.valueOf(o.toString());
			}
			return 0l;
		}
		
		private String getString(Object o){
			if(o!=null){
				return (String) o;
			}
			return "";
		}
		
		
		public YfSmsrecordService getYfSmsrecordService() {
			return yfSmsrecordService;
		}

		public void setYfSmsrecordService(YfSmsrecordService yfSmsrecordService) {
			this.yfSmsrecordService = yfSmsrecordService;
		}
    /**
     * 
    * 解析表达式
    *  "0 15 10 15 * ?"  
    * @param days
    * @return
     */
	public String getCronExpression(String hours)
	{
        //return "0 0/1 * * * ?";
		return "0 0 " + hours + " * * ?";
	}
	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}

	public void setSystemManagerService(SystemManagerService systemManagerService) {
		this.systemManagerService = systemManagerService;
	}

	public WorkFlowCommon getWorkFlowCommon() {
		return workFlowCommon;
	}

	public void setWorkFlowCommon(WorkFlowCommon workFlowCommon) {
		this.workFlowCommon = workFlowCommon;
	}
}
